package com.wangp.mywrite.coding;

/**
 * @description: 1234. 替换子串得到平衡字符串
 * @author tooStronger
 * @date 2023/2/13
 */
public class BalancedString {

    public int balancedString(String s) {
        char[] chars = s.toCharArray();
        int[] cnt = new int[26];
        for (char c : chars) {
            cnt[c - 'A']++;
        }
        int n = s.length(), m = n / 4;
        if (cnt['Q' - 'A'] == m && cnt['E' - 'A'] == m && cnt['W' - 'A'] == m && cnt['R' - 'A'] == m) {
            return 0;
        }
        int ans = n, left = 0;
        for (int right = 0; right < n; right++) {
            --cnt[chars[right] - 'A'];
            while(cnt['Q'-'A'] <= m && cnt['W'-'A'] <= m && cnt['E'-'A'] <= m && cnt['R'-'A'] <= m){
                ans  = Math.min(ans,right-left+1);
                ++cnt[chars[left++] - 'A'];
            }
        }
        return ans;
    }
}
